<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

import {
  getMarketListings,
  getOrders,
  getSellerProfile,
} from '#/api/resource-center';

// 响应式数据
const activeTab = ref('listings');
const showPublishModal = ref(false);

// 卖家统计数据
const sellerStats = ref({
  totalListings: 0,
  totalOrders: 0,
  totalRevenue: 0,
  rating: 0,
});

// 商品相关
const listingLoading = ref(false);
const listings = ref([]);
const listingFilter = reactive({
  status: undefined,
  category: undefined,
  keyword: '',
});
const listingPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 订单相关
const orderLoading = ref(false);
const orders = ref([]);
const orderFilter = reactive({
  status: undefined,
  dateRange: undefined,
  keyword: '',
});
const orderPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 分析数据
const analyticsData = ref([
  { metric: '今日访问量', value: 234 },
  { metric: '昨日访问量', value: 189 },
  { metric: '本月订单数', value: 45 },
  { metric: '上月订单数', value: 38 },
]);

// 卖家资料
const sellerProfile = reactive({
  name: '',
  phone: '',
  email: '',
  location: '',
  description: '',
});

// 表格列配置
const listingColumns = [
  { title: '商品信息', key: 'product', width: 300 },
  { title: '价格', key: 'price', width: 120 },
  { title: '统计', key: 'stats', width: 120 },
  { title: '状态', key: 'status', width: 100 },
  { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', width: 150 },
  { title: '操作', key: 'actions', width: 150, fixed: 'right' },
];

const orderColumns = [
  { title: '订单信息', key: 'order', width: 250 },
  { title: '买家', key: 'buyer', width: 150 },
  { title: '金额', key: 'amount', width: 120 },
  { title: '状态', key: 'status', width: 100 },
  { title: '操作', key: 'actions', width: 150, fixed: 'right' },
];

const analyticsColumns = [
  { title: '指标', dataIndex: 'metric', key: 'metric' },
  { title: '数值', dataIndex: 'value', key: 'value' },
];

// 格式化价格
const formatPrice = (price: number) => {
  if (price >= 10_000) {
    return `${(price / 10_000).toFixed(1)}万`;
  }
  return price.toLocaleString();
};

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString();
};

// 获取商品状态颜色
const getListingStatusColor = (status: string) => {
  const colorMap = {
    active: 'success',
    inactive: 'default',
    sold_out: 'warning',
  };
  return colorMap[status] || 'default';
};

// 获取商品状态名称
const getListingStatusName = (status: string) => {
  const nameMap = {
    active: '在售',
    inactive: '下架',
    sold_out: '售罄',
  };
  return nameMap[status] || status;
};

// 获取订单状态颜色
const getOrderStatusColor = (status: string) => {
  const colorMap = {
    pending_payment: 'orange',
    paid: 'blue',
    in_progress: 'processing',
    completed: 'success',
    cancelled: 'error',
  };
  return colorMap[status] || 'default';
};

// 获取卖家订单操作
const getSellerOrderActions = (order: any) => {
  const actions = [];

  switch (order.status) {
    case 'in_progress': {
      actions.push({ key: 'complete', label: '完成订单' });
      break;
    }
    case 'paid': {
      actions.push({ key: 'confirm', label: '确认订单' });
      break;
    }
  }

  return actions;
};

// 标签页切换
const handleTabChange = (key: string) => {
  activeTab.value = key;

  switch (key) {
    case 'analytics': {
      loadAnalytics();
      break;
    }
    case 'listings': {
      loadListings();
      break;
    }
    case 'orders': {
      loadOrders();
      break;
    }
    case 'settings': {
      loadProfile();
      break;
    }
  }
};

// 加载商品列表
const loadListings = async () => {
  listingLoading.value = true;
  try {
    const params = {
      ...listingFilter,
      sellerId: 'current_seller', // 当前卖家ID;sellerId
      page: listingPagination.current,
      pageSize: listingPagination.pageSize,
    };

    const result = await getMarketListings(params);
    listings.value = result.items || [];
    listingPagination.total = result.total || 0;
  } catch (error) {
    console.error('获取商品列表失败:', error);
    message.error('获取商品列表失败');
  } finally {
    listingLoading.value = false;
  }
};

// 加载订单列表
const loadOrders = async () => {
  orderLoading.value = true;
  try {
    const params = {
      ...orderFilter,
      sellerId: 'current_seller', // 当前卖家ID;sellerId
      page: orderPagination.current,
      pageSize: orderPagination.pageSize,
    };

    const result = await getOrders(params);
    orders.value = result.items || [];
    orderPagination.total = result.total || 0;
  } catch (error) {
    console.error('获取订单列表失败:', error);
    message.error('获取订单列表失败');
  } finally {
    orderLoading.value = false;
  }
};

// 加载分析数据
const loadAnalytics = () => {
  // 这里可以加载实际的分析数据
  console.log('加载分析数据');
};

// 加载卖家资料
const loadProfile = async () => {
  try {
    const result = await getSellerProfile('current_seller');
    Object.assign(sellerProfile, result);
  } catch (error) {
    console.error('获取卖家资料失败:', error);
  }
};

// 加载所有数据
const loadData = () => {
  // 加载统计数据
  sellerStats.value = {
    totalListings: 23,
    totalOrders: 156,
    totalRevenue: 12_560_000,
    rating: 4.8,
  };

  // 根据当前标签页加载对应数据
  handleTabChange(activeTab.value);
};

// 商品操作
const editListing = (listing: any) => {
  console.log('编辑商品:', listing.id);
  message.info('编辑商品功能开发中...');
};

const handleListingAction = ({ key }: { key: string }, listing: any) => {
  console.log('商品操作:', key, listing.id);

  switch (key) {
    case 'copy': {
      message.info('复制发布');
      break;
    }
    case 'delete': {
      message.info('删除商品');
      break;
    }
    case 'promote': {
      message.info('推广商品');
      break;
    }
    case 'toggle': {
      message.info(listing.status === 'active' ? '下架商品' : '上架商品');
      break;
    }
    case 'view': {
      message.info('查看详情');
      break;
    }
  }
};

// 订单操作
const viewOrderDetail = (order: any) => {
  console.log('查看订单详情:', order.id);
  message.info('查看订单详情');
};

const handleOrderAction = ({ key }: { key: string }, order: any) => {
  console.log('订单操作:', key, order.id);

  switch (key) {
    case 'complete': {
      message.info('完成订单');
      break;
    }
    case 'confirm': {
      message.info('确认订单');
      break;
    }
  }
};

// 表格变化处理
const handleListingTableChange = (pag: any) => {
  listingPagination.current = pag.current;
  listingPagination.pageSize = pag.pageSize;
  loadListings();
};

const handleOrderTableChange = (pag: any) => {
  orderPagination.current = pag.current;
  orderPagination.pageSize = pag.pageSize;
  loadOrders();
};

// 更新资料
const updateProfile = () => {
  console.log('更新卖家资料:', sellerProfile);
  message.success('资料更新成功');
};

// 初始化
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="seller-center">
    <!-- 页面头部 -->
    <div class="page-header">
      <a-row :gutter="24" align="middle">
        <a-col flex="1">
          <h2>卖家中心</h2>
          <p class="page-description">管理您的资源销售业务</p>
        </a-col>
        <a-col>
          <a-space>
            <a-button @click="loadData">
              <template #icon><SyncOutlined /></template>
              刷新
            </a-button>
            <a-button type="primary" @click="showPublishModal = true">
              <template #icon>
                <IconifyIcon icon="ant-design:plus-outlined" />
              </template>
              发布资源
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 卖家统计 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="在售商品"
            :value="sellerStats.totalListings"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix><ShopOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="总订单数"
            :value="sellerStats.totalOrders"
            :value-style="{ color: '#52c41a' }"
          >
            <template #prefix><FileTextOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="总收入"
            :value="sellerStats.totalRevenue"
            :precision="0"
            suffix="元"
            :value-style="{ color: '#f5222d' }"
          >
            <template #prefix><MoneyCollectOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="好评率"
            :value="sellerStats.rating"
            :precision="1"
            suffix="/5.0"
            :value-style="{ color: '#fa8c16' }"
          >
            <template #prefix><StarOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 功能标签页 -->
    <a-card size="small">
      <a-tabs v-model:active-key="activeTab" @change="handleTabChange">
        <!-- 我的商品 -->
        <a-tab-pane key="listings" tab="我的商品">
          <div class="tab-content">
            <!-- 商品筛选 -->
            <div class="filter-bar">
              <a-space>
                <a-select
                  v-model="listingFilter.status"
                  placeholder="商品状态"
                  style="width: 120px"
                  allow-clear
                  @change="loadListings"
                >
                  <a-select-option value="active">在售</a-select-option>
                  <a-select-option value="inactive">下架</a-select-option>
                  <a-select-option value="sold_out">售罄</a-select-option>
                </a-select>
                <a-select
                  v-model="listingFilter.category"
                  placeholder="商品分类"
                  style="width: 120px"
                  allow-clear
                  @change="loadListings"
                >
                  <a-select-option value="hotel">酒店资源</a-select-option>
                  <a-select-option value="restaurant">餐饮资源</a-select-option>
                  <a-select-option value="software">软件服务</a-select-option>
                  <a-select-option value="service">人力服务</a-select-option>
                </a-select>
                <a-input
                  v-model="listingFilter.keyword"
                  placeholder="搜索商品名称"
                  style="width: 200px"
                  allow-clear
                  @change="loadListings"
                />
              </a-space>
            </div>

            <!-- 商品列表 -->
            <a-table
              :columns="listingColumns"
              :data-source="listings"
              :loading="listingLoading"
              :pagination="listingPagination"
              row-key="id"
              @change="handleListingTableChange"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'product'">
                  <div class="product-info">
                    <a-space>
                      <a-avatar
                        :size="60"
                        :src="record.images[0] || '/images/placeholder.jpg'"
                        shape="square"
                      />
                      <div>
                        <div class="product-title">{{ record.title }}</div>
                        <div class="product-id">ID: {{ record.id }}</div>
                        <div class="product-category">
                          <a-tag size="small">{{ record.category }}</a-tag>
                        </div>
                      </div>
                    </a-space>
                  </div>
                </template>

                <template v-else-if="column.key === 'price'">
                  <div class="price-info">
                    <div class="current-price">
                      ¥{{ formatPrice(record.price.currentPrice) }}
                    </div>
                    <div class="price-unit">{{ record.price.unit }}</div>
                    <div v-if="record.price.negotiable" class="negotiable">
                      <a-tag color="blue" size="small">可议价</a-tag>
                    </div>
                  </div>
                </template>

                <template v-else-if="column.key === 'stats'">
                  <div class="stats-info">
                    <div>
                      <IconifyIcon icon="ant-design:eye-outlined" />
                      {{ record.views }}
                    </div>
                    <div><HeartOutlined /> {{ record.favorites }}</div>
                    <div><StarOutlined /> {{ record.ratings.average }}</div>
                  </div>
                </template>

                <template v-else-if="column.key === 'status'">
                  <a-tag :color="getListingStatusColor(record.status)">
                    {{ getListingStatusName(record.status) }}
                  </a-tag>
                </template>

                <template v-else-if="column.key === 'actions'">
                  <a-space>
                    <a-button size="small" @click="editListing(record)">
                      编辑
                    </a-button>
                    <a-dropdown>
                      <a-button size="small"> 更多 <DownOutlined /> </a-button>
                      <template #overlay>
                        <a-menu @click="handleListingAction($event, record)">
                          <a-menu-item key="view">查看详情</a-menu-item>
                          <a-menu-item key="copy">复制发布</a-menu-item>
                          <a-menu-item key="promote">推广</a-menu-item>
                          <a-menu-divider />
                          <a-menu-item
                            key="toggle"
                            :class="{ 'text-red': record.status === 'active' }"
                          >
                            {{ record.status === 'active' ? '下架' : '上架' }}
                          </a-menu-item>
                          <a-menu-item key="delete" class="text-red">
                            删除
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </template>
              </template>
            </a-table>
          </div>
        </a-tab-pane>

        <!-- 订单管理 -->
        <a-tab-pane key="orders" tab="订单管理">
          <div class="tab-content">
            <!-- 订单筛选 -->
            <div class="filter-bar">
              <a-space>
                <a-select
                  v-model="orderFilter.status"
                  placeholder="订单状态"
                  style="width: 120px"
                  allow-clear
                  @change="loadOrders"
                >
                  <a-select-option value="pending_payment">
                    待支付
                  </a-select-option>
                  <a-select-option value="paid">已支付</a-select-option>
                  <a-select-option value="in_progress">进行中</a-select-option>
                  <a-select-option value="completed">已完成</a-select-option>
                  <a-select-option value="cancelled">已取消</a-select-option>
                </a-select>
                <a-range-picker
                  v-model="orderFilter.dateRange"
                  placeholder="选择日期范围"
                  @change="loadOrders"
                />
                <a-input
                  v-model="orderFilter.keyword"
                  placeholder="搜索订单号或买家"
                  style="width: 200px"
                  allow-clear
                  @change="loadOrders"
                />
              </a-space>
            </div>

            <!-- 订单列表 -->
            <a-table
              :columns="orderColumns"
              :data-source="orders"
              :loading="orderLoading"
              :pagination="orderPagination"
              row-key="id"
              @change="handleOrderTableChange"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'order'">
                  <div class="order-info">
                    <div class="order-id">{{ record.id }}</div>
                    <div class="listing-title">{{ record.listingTitle }}</div>
                    <div class="order-time">
                      {{ formatDate(record.createdAt) }}
                    </div>
                  </div>
                </template>

                <template v-else-if="column.key === 'buyer'">
                  <div class="buyer-info">
                    <a-space>
                      <a-avatar :size="32" :src="record.buyer.avatar" />
                      <div>
                        <div>{{ record.buyer.name }}</div>
                        <div class="contact">{{ record.buyer.phone }}</div>
                      </div>
                    </a-space>
                  </div>
                </template>

                <template v-else-if="column.key === 'amount'">
                  <div class="amount-info">
                    <div class="total">
                      ¥{{ formatPrice(record.totalAmount) }}
                    </div>
                    <div class="paid">
                      已付: ¥{{ formatPrice(record.payment.paidAmount) }}
                    </div>
                  </div>
                </template>

                <template v-else-if="column.key === 'status'">
                  <a-tag :color="getOrderStatusColor(record.status)">
                    {{ record.statusName }}
                  </a-tag>
                </template>

                <template v-else-if="column.key === 'actions'">
                  <a-space>
                    <a-button size="small" @click="viewOrderDetail(record)">
                      详情
                    </a-button>
                    <a-dropdown v-if="getSellerOrderActions(record).length > 0">
                      <a-button size="small"> 操作 <DownOutlined /> </a-button>
                      <template #overlay>
                        <a-menu @click="handleOrderAction($event, record)">
                          <a-menu-item
                            v-for="action in getSellerOrderActions(record)"
                            :key="action.key"
                          >
                            {{ action.label }}
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </template>
              </template>
            </a-table>
          </div>
        </a-tab-pane>

        <!-- 数据分析 -->
        <a-tab-pane key="analytics" tab="数据分析">
          <div class="tab-content">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-card title="销售趋势" size="small">
                  <div class="chart-placeholder">销售趋势图表</div>
                </a-card>
              </a-col>
              <a-col :span="12">
                <a-card title="商品排行" size="small">
                  <div class="chart-placeholder">商品排行图表</div>
                </a-card>
              </a-col>
            </a-row>
            <a-row :gutter="16" style="margin-top: 16px">
              <a-col :span="24">
                <a-card title="详细数据" size="small">
                  <a-table
                    :columns="analyticsColumns"
                    :data-source="analyticsData"
                    :pagination="false"
                    size="small"
                  />
                </a-card>
              </a-col>
            </a-row>
          </div>
        </a-tab-pane>

        <!-- 账户设置 -->
        <a-tab-pane key="settings" tab="账户设置">
          <div class="tab-content">
            <a-form
              :model="sellerProfile"
              layout="vertical"
              @finish="updateProfile"
            >
              <a-row :gutter="24">
                <a-col :span="12">
                  <a-form-item label="卖家名称" name="name">
                    <a-input v-model="sellerProfile.name" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="联系电话" name="phone">
                    <a-input v-model="sellerProfile.phone" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="12">
                  <a-form-item label="邮箱地址" name="email">
                    <a-input v-model="sellerProfile.email" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="所在地区" name="location">
                    <a-input v-model="sellerProfile.location" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-form-item label="公司描述" name="description">
                <a-textarea
                  v-model="sellerProfile.description"
                  :rows="4"
                  placeholder="请输入公司或个人简介"
                />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" html-type="submit">
                  保存设置
                </a-button>
              </a-form-item>
            </a-form>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 发布资源弹窗 -->
    <a-modal
      v-model:visible="showPublishModal"
      title="发布资源"
      width="800px"
      :footer="null"
    >
      <p>发布资源功能开发中...</p>
    </a-modal>
  </div>
</template>

<style scoped>
.seller-center {
  padding: 16px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-description {
  margin: 4px 0 0;
  font-size: 14px;
  color: #6b7280;
}

.stats-row {
  margin-bottom: 24px;
}

.tab-content {
  padding: 16px 0;
}

.filter-bar {
  padding: 12px;
  margin-bottom: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-title {
  margin-bottom: 4px;
  font-weight: 500;
  color: #1f2937;
}

.product-id {
  margin-bottom: 4px;
  font-size: 12px;
  color: #6b7280;
}

.product-category {
  font-size: 12px;
}

.price-info {
  text-align: right;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #f5222d;
}

.price-unit {
  margin-top: 2px;
  font-size: 12px;
  color: #6b7280;
}

.negotiable {
  margin-top: 4px;
}

.stats-info {
  font-size: 12px;
  color: #6b7280;
}

.stats-info > div {
  margin-bottom: 2px;
}

.order-info {
  padding: 4px 0;
}

.order-id {
  margin-bottom: 4px;
  font-weight: 500;
  color: #1f2937;
}

.listing-title {
  margin-bottom: 4px;
  font-size: 12px;
  color: #6b7280;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.buyer-info {
  display: flex;
  align-items: center;
}

.contact {
  font-size: 12px;
  color: #6b7280;
}

.amount-info {
  text-align: right;
}

.total {
  font-size: 16px;
  font-weight: 600;
  color: #f5222d;
}

.paid {
  margin-top: 2px;
  font-size: 12px;
  color: #52c41a;
}

.chart-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
  background: #fafafa;
  border-radius: 6px;
}

.text-red {
  color: #f5222d;
}
</style>
